﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace MQ.Common
{
    public class RabbitHelper
    {
        private readonly RabbitMQConfig Config = null;
        public RabbitHelper(RabbitMQConfig config)
        {
            Config = config;
        }

        public IConnection GetConnection() =>
            new ConnectionFactory()
            {
                HostName = Config.HostName,
                Port = Config.Port,
                UserName = Config.UserName,
                Password = Config.Password,
                RequestedConnectionTimeout = TimeSpan.FromSeconds(10),//超时时间
                AutomaticRecoveryEnabled = true, //恢复连接机制 true 开启
            }.CreateConnection();

        /// <summary>
        /// 生产者发送消息
        /// </summary>
        /// <param name="queue"></param>
        /// <param name="routingKey"></param>
        /// <param name="exchange"></param>
        /// <param name="exchangeType"></param>
        public void SendMessage(string queue, string routingKey, bool durable = false, string? exchange = null, string? exchangeType = null)
        {
            var conn = GetConnection();
            {
                var channel = conn.CreateModel();
                {
                    //声明交换机
                    if (string.IsNullOrWhiteSpace(exchange))
                        channel.ExchangeDeclare(exchange, exchangeType, false, false, null);
                    //声明队列
                    if (string.IsNullOrWhiteSpace(queue))
                        throw new Exception("队列名不能为空!");
                }
            }
        }

    }
}
